<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>聊天记录</title>

    <link rel="stylesheet" href="../../../layui.css">
    <style>
        body .layim-chat-main{height: auto;}
        .layim-chat-main{display: inline-block;}
        .layui-laypage{margin-top: 5px;}
        hr{margin-bottom: 0px;}
        .layui-card-footer{
            border-top: 1px solid #ffd872;
            text-align: center;
            height: 28px;
            line-height: 28px;
            vertical-align: middle;
        }
        .layui-card-footer a{
            color: #00b5f9!important;
        }
    </style>
</head>
    <body>
        <form class="layui-form layui-form-pane" onsubmit="return false" id="form" lay-filter="form">
            <div class="layui-row layui-col-space15">
                <div class="layui-col-xs1 layui-col-md1"></div>
                <div class="layui-col-xs10 layui-col-md10"></div>
                <div class="layui-col-xs1 layui-col-md1"></div>
            </div>

            <div class="layui-row layui-col-space15">
                <div class="layui-col-xs1 layui-col-md1"></div>
                <div class="layui-col-xs10 layui-col-md10">
                    <label class="layui-form-label">消息内容</label>
                    <div class="layui-input-block">
                        <input type="text" id="content" name="content" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-xs1 layui-col-md1"></div>
            </div>

            <div class="layui-row layui-col-space15">
                <div class="layui-col-xs1 layui-col-md1">
                </div>
                <div class="layui-col-xs5 layui-col-md5">
                    <div class="layui-input-line">
                        <input type="text" id="startTime" name="startTime" placeholder="起始时间" required="" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-xs5 layui-col-md5">
                    <div class="layui-input-line">
                        <input type="text" id="endTime" name="endTime" placeholder="结束时间" required="" lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-xs1 layui-col-md1">
                </div>
            </div>

            <div class="layui-row layui-col-space15">
                <div class="layui-col-xs12 layui-col-md12">
                    <hr>
                </div>
            </div>

            <div class="layui-row layui-col-space15">
                <div class="layui-col-xs7 layui-col-md9">
                </div>
                <div class="layui-col-xs4 layui-col-md2">
                    <button type="submit" class="layui-btn layui-btn-fluid layui-btn-default" lay-submit="" lay-filter="search_btn" id="search_btn">搜索</button>
                </div>
                <div class="layui-col-xs1 layui-col-md1">
                </div>
            </div>
        </form>

        <div class="layim-chat-main" style="width: 97%;">
            <ul id="LAY_view"></ul>
        </div>

        <hr>

        <div id="LAY_page" style="margin: 0 10px;"></div>

        <textarea title="消息模版" id="LAY_tpl" style="display:none;">
        {{# layui.each(d.data, function(index, item){
          if(item.mine){ }}
            <li class="layim-chat-mine"><div class="layim-chat-user"><img src="{{ item.avatar }}"><cite><i>{{ layui.data.date(item.timestamp) }}</i>{{ item.username }}</cite></div><div class="layim-chat-text">{{ layui.layim.content(item.content) }}</div></li>
          {{# } else { }}
            <li><div class="layim-chat-user"><img src="{{ item.avatar }}"><cite>{{ item.username }}<i>{{ layui.data.date(item.timestamp) }}</i></cite></div><div class="layim-chat-text">{{ layui.layim.content(item.content) }}</div></li>
          {{# }
        }); }}
        </textarea>

        <!--
        上述模版采用了 laytpl 语法，不了解的同学可以去看下文档：http://www.layui.com/doc/modules/laytpl.html
        -->

        <script src="../../../../../../static/js/config.js" type="text/javascript"></script>

        <script src="../../../../layui.js"></script>
        <script>
            layui.use(['Utils', 'layim', 'laypage', 'http', 'laydate', 'form'], function(){
                var layim = layui.layim
                    ,layer = layui.layer
                    ,laytpl = layui.laytpl
                    ,$ = layui.jquery
                    ,laypage = layui.laypage
                    ,http = layui.http
                    ,laydate = layui.laydate
                    ,form = layui.form
                    Utils = layui.Utils;

                var groupId = QueryParam.get("id").split("_")[0],
                    userId = QueryParam.get("id").split("_")[1],
                    communicationId = QueryParam.get("communicationId"),
                    useRecordId = QueryParam.get("useRecordId"),
                    startTime = QueryParam.get("startTime"),
                    isHistory = QueryParam.get("isHistory");

                $(".layim-chat-main").height($(window).height() - 210 - 70);

                form.val('form',{
                    startTime: startTime ? startTime : DateUtil.format(new Date().getTime() - 1000 * 60 * 60 * 24 * 3, "yyyy-MM-dd 00:00:00"),
                    endTime: DateUtil.format(new Date(), "yyyy-MM-dd 23:59:59")
                });

                laydate.render({
                    elem: '#startTime' //指定元素
                    ,type: 'datetime'
                });

                laydate.render({
                    elem: '#endTime' //指定元素
                    ,type: 'datetime'
                });

                form.on('submit(search_btn)', function(data) {

                     var result_ = refreshTable(1);

                    laypage.render({
                        elem: 'LAY_page'
                        ,groups: 2
                        ,count: result_.count
                        ,layout: ['prev', 'page', 'next', 'count']
                        ,curr: result_.pageNo
                        ,jump: function(obj, first){
                            //首次不执行
                            if(!first){
                                refreshTable(obj.curr);
                            }
                        }
                    });
                })

                $("#search_btn").click();

                function refreshTable(pageNo){

                    var result_ = null;

                    var formData = form.val('form');

                    http.post({
                        url: '/im/message/getMessageHistory',
                        async: false,
                        data: {
                            "talkType": groupId,
                            "queryId": isHistory ? userId : SessionUtils.getLoginAccount().user.id,
                            "communicationId": communicationId ? communicationId : '',
                            "startTime": formData.startTime.replace(" ", "T"),
                            "endTime": formData.endTime.replace(" ", "T"),
                            "content": formData.content,
                            "useRecordId": useRecordId ? useRecordId : '',
                            "page":{
                                "pageSize": "10",
                                "pageNo": pageNo
                            }
                        },
                        backFun: function(result){

                            result_ = result;

                            var arr = [];
                            var record = null;
                            var content = null;
                            var mine = false;
                            //list is empty
                            if(DataVerify.isUndefined(result.list)){
                                return;
                            }
                            for(var i = 0; i < result.list.length; i++){

                                record = result.list[i];

                                content = record.content;

                                if(!content || content.length <= 0) continue;

                                if(GLOBAL.MSG_CONTENT_TYPE.IMAGE == record.contentType){
                                    content = "img[" + Appendix.getDownLoadUrl(record.content) + "]"
                                }else if(GLOBAL.MSG_CONTENT_TYPE.JSON == record.contentType){
                                    var jsonObject = JSON.parse(content);
                                    content =  'html<div class="layui-card" style="width: 300px">' +
                                                        '<div class="layui-card-body">' +
                                                             jsonObject.name +
                                                            '<br>' +
                                                            '<span style="font-size: 14px;color: #FFB800">' + jsonObject.price + '(元)</span>' +
                                                        '</div>' +
                                                        '<div class="layui-card-footer">' +
                                                            '<a href="javascript:top.openIMProductDetailWin(\'' + jsonObject.talkType + '\',\'' + jsonObject.type + '\',\'' + jsonObject.id + '\',\'' + jsonObject.useRecordId + '\',\'' + jsonObject.buyerId + '\',\'' + jsonObject.memberServiceType + '\',\'' + jsonObject.memberServiceId + '\',\'' + jsonObject.serviceType + '\');">点击查看详情</a>' +
                                                        '</div>' +
                                                    '</div>'
                                }

                                //其他服务者发送和自己发送的都统一放在右边
                                if((record.initiatorId != SessionUtils.getLoginAccount().user.id && record.recipientId != SessionUtils.getLoginAccount().user.id) ||
                                    record.initiatorId == SessionUtils.getLoginAccount().user.id){
                                    mine = true;
                                }else{
                                    mine = false;
                                }

                                arr.push({
                                    username: record.initiatorDetail ? record.initiatorDetail.userName : "" //消息来源用户名
                                    ,avatar: record.initiatorDetail ? record.initiatorDetail.url : "" //消息来源用户头像
                                    ,id: record.talkType + "_" + record.initiatorId //消息的来源ID（如果是私聊，则是用户id，如果是群聊，则是群组id）
                                    ,type: "friend" //聊天窗口来源类型，从发送消息传递的to里面获取
                                    ,content: content //消息内容
                                    ,cid: record.id //消息id，可不传。除非你要对消息进行一些操作（如撤回）
                                    ,mine: mine ? true : false //是否我发送的消息，如果为true，则会显示在右方
                                    ,fromid: record.talkType + "_" + record.initiatorId //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
                                    ,timestamp: record.sendDate //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
                                })
                            }

                            var html = "";
                            if(result.list && result.list.length > 0){
                                html = laytpl(LAY_tpl.value).render({
                                    data: arr
                                });
                            }

                            $('#LAY_view').html(html);
                        }});

                    return result_;
                }

            });
        </script>
    </body>
</html>
